﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Media;

namespace WebCamWorker.ViewModel
{
    public class VMButterflyDemo : INotifyPropertyChanged
    {
        private double leftWingAngle;
        /// <summary>
        /// Угол наклона левого крыла
        /// </summary>
        public double LeftWingAngle
        {
            get
            {
                return leftWingAngle;
            }
            set
            {
                // if (value >= 0 && value <= 90)
                {
                    leftWingAngle = value;
                    OnPropertyChanged("LeftWingAngle");
                }
            }
        }

        private double rightWindAngle;
        /// <summary>
        /// Угол наклона правого крыла
        /// </summary>
        public double RightWingAngle
        {
            get
            {
                return rightWindAngle;
            }
            set
            {
                // if (value >= 0 && value <= 90)
                {
                    rightWindAngle = value;
                    OnPropertyChanged("RightWingAngle");
                }
            }
        }

        public void MotionCaptureImageFormed(Bitmap outputImage, double leftAngle, double rightAngle)
        {
            Image = loadBitmap(outputImage);
            LeftWingAngle = leftAngle*180/Math.PI;
            RightWingAngle = rightAngle*180/Math.PI;
            
        }

        private ImageSource source;
        public ImageSource Image
        {
            get { return source; }
            private set { source = value; OnPropertyChanged("Image"); }
        }

        [DllImport("gdi32")]
        static extern int DeleteObject(IntPtr o);

        private static BitmapSource loadBitmap(System.Drawing.Bitmap source)
        {
            IntPtr ip = source.GetHbitmap();
            BitmapSource bs = null;
            try
            {
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
                   IntPtr.Zero, Int32Rect.Empty,
                   System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            }
            finally
            {
                DeleteObject(ip);
            }

            return bs;
        }

        protected void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
